const Consul = require('consul')
const ip = require('ip')
const axios = require('axios').default
module.exports = ({ config, logger }) => {
  const consul = new Consul({
    host: config.consul.host,
    port: config.consul.port,
    promisify: true,
  })

  return {
    register: async () => {
      try {
        logger.info(
          `服务 ${config.serviceName}正在注册到 ${config.consul.host}:${config.consul.port}`
        )
        const res = await consul.agent.service.register({
          name: config.serviceName,
          address: ip.address(),
          port: config.port,
          check: {
            http: `http://${ip.address()}:${config.port}/health`,
            interval: '5s',
          },
        })
        logger.info('服务注册成功')
      } catch (e) {
        logger.error('服务注册失败', e)
      }
    },
    async getSerice(name) {
      const serviceMap = await consul.agent.services()
      const service = serviceMap[name]
      return service
    },
    consul,
  }
}
